/**
 *
 */
package com.ybkj.daijia.server.service.impl;


import com.ybkj.daijia.server.mapper.PlaceInputHistoryMapper;
import com.ybkj.daijia.server.model.PlaceInputHistory;
import com.ybkj.daijia.server.service.PlaceInputHistoryService;
import java.util.LinkedList;
import java.util.List;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Shine
 *
 */
@Service
public class DefaultPlaceInputHistoryService implements PlaceInputHistoryService {

    @Autowired
    private PlaceInputHistoryMapper placeInputHistoryMapper;

    @Override
    public List<PlaceInputHistory> findByKeywords(String keyword) {

        keyword = StringUtils.trimToNull(keyword);

        if (StringUtils.isEmpty(keyword)) {
            return new LinkedList<PlaceInputHistory>();
        }

        return placeInputHistoryMapper.selectByNameLike("%" + keyword + "%");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PlaceInputHistory insertRecord(PlaceInputHistory record) {

        String address = StringUtils.trim(record.getAddress());
        record.setAddress(address);

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 没有声调
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 小写
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        if (StringUtils.isNotBlank(address)) {
            StringBuilder sb = new StringBuilder();
            for (char ch : address.toCharArray()) {
                try {
                    String results[] = PinyinHelper.toHanyuPinyinStringArray(ch, format);
                    if (ArrayUtils.isNotEmpty(results)) {
                        String pinying = results[0];
                        sb.append(pinying.charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }
            record.setPinyin(sb.toString());
        }

        placeInputHistoryMapper.insertRecord(record);

        return record;
    }

    @Override
    public PlaceInputHistory findByAddress(String address) {

        return placeInputHistoryMapper.selectByAddress(address);
    }

}